<template>
  <view class="page">
    <!-- 导航栏 -->
    <view class="nav-bar" :style="{ paddingTop: statusBarPx + 'px' }">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <uv-icon name="arrow-left" size="30" color="#303133"></uv-icon>
        </view>
        <view class="nav-title">详情</view>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <input
          class="search-input"
          type="text"
          v-model="searchAddress"
          placeholder="输入地址搜索"
          placeholder-style="color: #909399"
          @confirm="handleSearch"
        />
        <view class="search-btn" @click="handleSearch">
          <text class="search-btn-text">搜索</text>
        </view>
      </view>
    </view>

    <!-- 顶部总价值卡片 - 带渐变背景 -->
    <view class="value-card">
      <view class="value-card-content">
        <!-- 链上地址区域 -->
        <view class="address-section" v-if="userAddress">
          <view class="address-row">
            <text class="address-label">链上地址：</text>
            <text class="address-value">{{ userAddress }}</text>
            <view class="copy-btn" @click="copyAddress">
              <uv-icon name="file-text" size="16" color="#ffffff"></uv-icon>
              <text class="copy-text">复制</text>
            </view>
          </view>
        </view>
<!--         
        <text class="value-label">永续合约仓位价值</text>
        <text class="value-amount">{{ totalValue }}</text> -->
      </view>
      <view class="value-card-bg"></view>
    </view>

    <!-- Tab切换栏 - 带动画指示器和粘性布局 -->
    <view class="tab-bar" :style="{ top: tabBarTop }">
      <view
        class="tab-item"
        v-for="(tab, idx) in tabList"
        :key="idx"
        :class="{ active: activeTab === idx }"
        @click="onTabClick(idx)"
      >
        <text class="tab-text">
          {{ idx === 2 && orderList.length > 0 ? `${tab}(${orderList.length})` : tab }}
        </text>
      </view>
      <view
        class="tab-indicator"
        :style="{ left: `calc(${activeTab * 25}% + 8rpx)` }"
      ></view>
    </view>

    <!-- Tab内容区域 - 带淡入淡出动画 -->
    <scroll-view class="tab-content" scroll-y>
      <!-- 持仓 Tab -->
      <view v-if="activeTab === 0" class="position-tab fade-in">
        <!-- 加载中 -->
        <view v-if="isPositionLoading" class="loading-container">
          <uv-loading-icon mode="circle" color="#00d4aa" size="40"></uv-loading-icon>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 空状态 -->
        <view v-else-if="positionList.length === 0" class="empty-state">
          <text class="empty-text">暂无持仓记录</text>
        </view>

        <!-- 持仓列表 -->
        <view v-else class="position-list">
          <view 
            class="position-item" 
            v-for="(item, idx) in positionList" 
            :key="idx"
          >
            <!-- 币种和方向标识 -->
            <view class="position-header">
              <view class="side-badge" :class="item.side === 'long' ? 'long' : 'short'">
                <text class="side-text">{{ item.side === 'long' ? '多' : '空' }}</text>
              </view>
              <text class="coin-name">{{ item.coin }}</text>
            </view>
            <view class="position-row">
              <view class="position-col">
                <text class="label">未实现盈亏(USDT)</text>
                <text :class="['value', 'pnl', parseFloat(item.unrealizedPnl) === 0 ? '' : (parseFloat(item.unrealizedPnl) > 0 ? 'profit' : 'loss')]">
                  {{ formatPnl(item.unrealizedPnl) }}
                </text>
              </view>
              <view class="position-col">
                <text class="label">杠杆</text>
                <text class="value leverage">{{ item.typeValue }} 全仓</text>
              </view>
            </view>
            <!-- 第一行：数量、价值、资金费 -->
            <view class="position-row">
              <view class="position-col">
                <text class="label">数量</text>
                <text class="value">{{ formatQuantity(item.szi, item.coin, item.side) }}</text>
              </view>
              <view class="position-col">
                <text class="label">价值</text>
                <text class="value">{{ formatValue(item.positionValue) }}</text>
              </view>
              <view class="position-col">
                <text class="label">资金费</text>
                <text :class="['value', 'funding-fee', parseFloat(item.sinceOpen) === 0 ? '' : (parseFloat(item.sinceOpen) > 0 ? 'profit' : 'loss')]">
                  {{ formatFundingFee(item.sinceOpen) }}
                </text>
              </view>
            </view>

            <!-- 第二行：开仓价格、保证金、爆仓价格 -->
            <view class="position-row">
              <view class="position-col">
                <text class="label">开仓价格</text>
                <text class="value">${{ formatPrice(item.entryPx) }}</text>
              </view>
              <view class="position-col">
                <text class="label">杠杆</text>
                <text class="value">{{ formatGG(item.typeValue) }}</text>
              </view>
              <view class="position-col">
                <text class="label">爆仓价格</text>
                <text class="value">${{ formatPrice(item.liquidationPx) }}</text>
              </view>
            </view>

            <!-- 第三行：未实现盈亏和杠杆 -->

          </view>
        </view>
      </view>

      <!-- 交易 Tab -->
      <view v-if="activeTab === 1" class="trade-tab fade-in">
        <!-- 加载中 -->
        <view v-if="isTradeLoading" class="loading-container">
          <uv-loading-icon mode="circle" color="#00d4aa" size="40"></uv-loading-icon>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 空状态 -->
        <view v-else-if="tradeList.length === 0" class="empty-state">
          <text class="empty-text">暂无交易记录</text>
        </view>

        <!-- 交易列表 -->
        <view v-else class="trade-list">
          <!-- 交易项 -->
          <view 
            class="trade-item" 
            v-for="(item, idx) in tradeList" 
            :key="idx"
          >
            <!-- 第一行：方向标识 + 哈希地址 -->
            <view class="trade-header">
              <view class="trade-dir-badge" :class="isBuyDir(item.dir) ? 'buy' : 'sell'">
                <text class="dir-text">{{ isBuyDir(item.dir) ? '买' : '卖' }}</text>
              </view>
              <text class="trade-hash" v-if="item.hash">{{ item.hash || '--' }}</text>
            </view>

            <!-- 第二行：数量 | 操作 -->
            <view class="trade-row">
              <view class="trade-col">
                <text class="trade-label">数量</text>
                <text class="trade-quantity" :class="!isBuyDir(item.dir) ? 'sell-quantity' : ''">
                  {{ formatTradeQuantity(item.sz, item.coin, item.dir) }}
                </text>
              </view>
              <view class="trade-col">
                <text class="trade-label">操作</text>
                <text class="trade-operation">{{ formatDir(item.dir) }}</text>
              </view>
            </view>

            <!-- 第三行：价值(USDT) | 价格(USDT) | 时间 -->
            <view class="trade-row">
              <view class="trade-col">
                <text class="trade-label">价值(USDT)</text>
                <text class="trade-value">${{ formatPrice(item.val) }}</text>
              </view>
              <view class="trade-col">
                <text class="trade-label">价格(USDT)</text>
                <text class="trade-price">${{ formatPrice(item.px) }}</text>
              </view>
              <view class="trade-col">
                <text class="trade-label">时间</text>
                <text class="trade-time">{{ formatTime(item.time) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 当前委托 Tab -->
      <view v-if="activeTab === 2" class="order-tab fade-in">
        <!-- 加载中 -->
        <view v-if="isOrderLoading" class="loading-container">
          <uv-loading-icon mode="circle" color="#00d4aa" size="40"></uv-loading-icon>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 空状态 -->
        <view v-else-if="orderList.length === 0" class="empty-state">
          <text class="empty-text">暂无委托记录</text>
        </view>

        <!-- 委托列表 -->
        <view v-else class="order-list">
          <view 
            class="order-item" 
            v-for="(item, idx) in orderList" 
            :key="idx"
          >
            <!-- 币种和方向标识 -->
            <view class="order-header">
              <view class="order-dir-badge" :class="item.side === 'long' ? 'long' : 'short'">
                <text class="order-dir-text">{{ item.reduceOnly === '卖出' ? '空' : '多' }}</text>
              </view>
              <text class="order-coin">{{ item.coin }}</text>
            </view>

            <!-- 第二行：数量 | 价格 | 操作 -->
            <view class="order-row">
              <view class="order-col">
                <text class="label">数量</text>
                <text class="value">{{ formatOrderQuantity(item.origSz, item.coin) }}</text>
              </view>
              <view class="order-col">
                <text class="label">价格</text>
                <text class="value">${{ formatPrice(item.limitPx || item.triggerPx) }}</text>
              </view>
              <view class="order-col">
                <text class="label">操作</text>
                <text class="value order-type">{{ formatOrderType(item.orderType) }}</text>
              </view>
            </view>

            <!-- 第三行：触发价格 | 时间 | ID -->
            <view class="order-row">
              <view class="order-col">
                <text class="label">触发价格</text>
                <text class="value">${{ formatPrice(item.triggerPx) }}</text>
              </view>
              <view class="order-col">
                <text class="label">时间</text>
                <text class="value">{{ formatTime(item.time) }}</text>
              </view>
              <view class="order-col">
                <text class="label">ID</text>
                <text class="value order-id">{{ item.oid }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 充值&提现 Tab -->
      <view v-if="activeTab === 3" class="recharge-tab fade-in">
        <!-- 加载中 -->
        <view v-if="isRechargeLoading" class="loading-container">
          <uv-loading-icon mode="circle" color="#00d4aa" size="40"></uv-loading-icon>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 空状态 -->
        <view v-else-if="rechargeList.length === 0" class="empty-state">
          <text class="empty-text">暂无充值提现记录</text>
        </view>

        <!-- 充值提现列表 -->
        <view v-else class="recharge-list">
          <view 
            class="recharge-item" 
            v-for="(item, idx) in rechargeList" 
            :key="idx"
          >
            <!-- 两行布局：第一行（时间 | 操作），第二行（价值 | 哈希） -->
            <view class="recharge-row">
              <view class="recharge-col">
                <text class="recharge-label">时间</text>
                <text class="recharge-value">{{ formatTime(item.time) }}</text>
              </view>
              <view class="recharge-col">
                <text class="recharge-label">操作</text>
                <text class="recharge-value recharge-type">{{ formatRechargeType(item.type) }}</text>
              </view>
            </view>

            <view class="recharge-row">
              <view class="recharge-col">
                <text class="recharge-label">价值</text>
                <text class="recharge-value">{{ formatRechargeValue(item.usdc) }}</text>
              </view>
              <view class="recharge-col">
                <text class="recharge-label">哈希</text>
                <text class="recharge-value recharge-hash">{{ item.hash || '--' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getRechargeWithdraw, getTrade, getPosition, getOrder, getCelebrityDetail } from '@/api/data'
import {
  formatPrice as formatPriceUtil,
  formatValue as formatValueUtil,
  formatSignedAmount,
  formatCurrency
} from '@/utils/number-formatter'

// 使用公共工具函数进行数字格式化

export default {
  data() {
    const sys = uni.getSystemInfoSync()
    const statusBarPx = sys.statusBarHeight || 0

    // 计算 tab-bar 的 top 值（只考虑状态栏高度）
    const tabBarTop = `${statusBarPx}px`

    return {
      statusBarPx,
      tabBarTop,
      celebrityId: null, // 名人ID
      userAddress: '', // 用户地址
      searchAddress: '', // 搜索的地址
      totalValue: '$5.24亿', // 总价值（可以动态计算）
      currenciesMap: {}, // 币种映射表（symbol -> logoUrl）

      // Tab切换
      activeTab: 0, // 0=持仓, 1=交易, 2=当前委托, 3=充值&提现
      tabList: ['仓位', '交易', '当前委托', '充值&提现'],

      // 各tab数据
      positionList: [], // 持仓列表
      tradeList: [], // 交易列表
      orderList: [], // 委托列表
      rechargeList: [], // 充值提现列表

      // 加载状态
      isPositionLoading: false,
      isTradeLoading: false,
      isOrderLoading: false,
      isRechargeLoading: false,

      // 币种图标映射
      coinIconMap: {
        'BTC': 'https://cryptologos.cc/logos/bitcoin-btc-logo.png',
        'ETH': 'https://cryptologos.cc/logos/ethereum-eth-logo.png',
        'USDT': 'https://cryptologos.cc/logos/tether-usdt-logo.png',
        'SOL': 'https://cryptologos.cc/logos/solana-sol-logo.png',
        'DOGE': 'https://cryptologos.cc/logos/dogecoin-doge-logo.png',
      },
    }
  },

  async onLoad(options) {
    // 优先处理ID参数（新逻辑）
    if (options.id) {
      this.celebrityId = options.id
      console.log('名人ID:', this.celebrityId)

      // 根据ID获取名人详情（包含地址）
      await this.loadCelebrityDetail()

      // 如果成功获取到地址，加载持仓数据
      if (this.userAddress) {
        this.loadPositionData()
      }
    }
    // 兼容旧的地址参数逻辑
    else if (options.address) {
      this.userAddress = decodeURIComponent(options.address)
      console.log('用户地址:', this.userAddress)

      // 默认加载持仓数据
      this.loadPositionData()
    } else {
      uni.showToast({
        title: '缺少参数',
        icon: 'none'
      })
    }
  },
  
  methods: {
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },

    /**
     * 根据ID加载名人详情
     */
    async loadCelebrityDetail() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })

        const response = await getCelebrityDetail({
          id: this.celebrityId
        })

        console.log('名人详情响应:', response)

        if (response.code === 200 && response.data) {
          const celebrity = response.data

          // 获取链上地址
          if (celebrity.publicChainAddress) {
            this.userAddress = celebrity.publicChainAddress
            console.log('获取到链上地址:', this.userAddress)
          } else {
            uni.showToast({
              title: '该名人暂无链上地址',
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          throw new Error(response.msg || '获取名人详情失败')
        }
      } catch (error) {
        console.error('加载名人详情失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none',
          duration: 2000
        })
      } finally {
        uni.hideLoading()
      }
    },

    /**
     * 处理搜索
     * @description 用户输入地址后点击搜索，更新当前页面的详情数据
     */
    handleSearch() {
      // 去除首尾空格
      const address = (this.searchAddress || '').trim()

      // 验证地址是否为空
      if (!address) {
        uni.showToast({
          title: '请输入地址',
          icon: 'none',
          duration: 2000
        })
        return
      }

      // 基本验证：地址长度至少10个字符（以太坊地址通常是42个字符，但这里做宽松验证）
      if (address.length < 10) {
        uni.showToast({
          title: '地址格式不正确',
          icon: 'none',
          duration: 2000
        })
        return
      }

      // 更新当前页面的地址并重新加载数据
      this.userAddress = address
      this.searchAddress = '' // 清空搜索框

      // 清空所有tab的数据
      this.positionList = []
      this.tradeList = []
      this.orderList = []
      this.rechargeList = []

      // 根据当前激活的tab重新加载对应数据
      switch (this.activeTab) {
        case 0:
          this.loadPositionData()
          break
        case 1:
          this.loadTradeData()
          break
        case 2:
          this.loadOrderData()
          break
        case 3:
          this.loadRechargeData()
          break
        default:
          this.loadPositionData()
      }
    },


    /**
     * Tab切换 - 每次切换都调用最新接口
     */
    onTabClick(index) {
      if (this.activeTab === index) return

      this.activeTab = index

      // 根据tab加载对应数据（每次切换都重新加载最新数据）
      switch (index) {
        case 0:
          this.loadPositionData()
          break
        case 1:
          this.loadTradeData()
          break
        case 2:
          this.loadOrderData()
          break
        case 3:
          this.loadRechargeData()
          break
      }
    },

    /**
     * 上拉刷新当前tab数据
     */
    onPullDownRefresh() {
      switch (this.activeTab) {
        case 0:
          this.loadPositionData()
          break
        case 1:
          this.loadTradeData()
          break
        case 2:
          this.loadOrderData()
          break
        case 3:
          this.loadRechargeData()
          break
      }
    },
    formatGG(typeValue) {
        // typeValue 是 "15X cross" 时，转换成 "15X全仓"
        if (typeValue.includes('cross')) {
            return typeValue.split(' ')[0] + '全仓'
        }
        return typeValue
      
    },
    /**
     * 加载持仓数据
     */
    async loadPositionData() {
      try {
        this.isPositionLoading = true
        
        // 使用真实API
        const response = await getPosition({
          address: this.userAddress
        })
        console.log('持仓数据:', response)
        const records = response.data || []
        
        this.positionList = records.map(item => ({
          coin: item.coin || '',
          typeValue: item.typeValue || '10',
          szi: item.szi || '0',
          side: (item.side || 'long').toLowerCase(),
          positionValue: item.positionValue || '0',
          entryPx: item.entryPx || '0',
          unrealizedPnl: item.unrealizedPnl || '0',
          sinceOpen: item.sinceOpen || '0', // 资金费
          liquidationPx: item.liquidationPx || '0',
          marginBalance: item.marginBalance || '0', // 保证金
          logoUrl: item.logoUrl || ''
        }))
      } catch (error) {
        console.error('加载持仓数据失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.isPositionLoading = false
        uni.stopPullDownRefresh()
      }
    },

    /**
     * 加载交易数据
     */
    async loadTradeData() {
      try {
        this.isTradeLoading = true

        // 使用真实API
        const response = await getTrade({
          address: this.userAddress
        })
        console.log('交易数据:', response)
        const records = response.data || []

        this.tradeList = records.map(item => ({
          dir: item.dir,
          coin: item.coin || '',
          time: item.time || '',
          sz: item.sz || '0',
          px: item.px || '0',
          val: item.val || '0', // 价值
          logoUrl: item.logoUrl || ''
        }))
      } catch (error) {
        console.error('加载交易数据失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.isTradeLoading = false
        uni.stopPullDownRefresh()
      }
    },
    
    /**
     * 加载委托数据
     */
    async loadOrderData() {
      try {
        this.isOrderLoading = true
        
        // 使用真实API
        const response = await getOrder({
          address: this.userAddress
        })
        console.log('委托数据:', response)
        const records = response.data || []
        
          this.orderList = records.map(item => ({
            reduceOnly: item.reduceOnly || '',
            oid: item.oid || '',
            coin: item.coin || '',
            time: item.time || '',
            orderType: item.orderType || 'limit',
            origSz: item.origSz || '0',
            limitPx: item.limitPx || '',
            triggerPx: item.triggerPx || '',
            orderId: item.orderId || item.id || String(item.timestamp || ''), // 订单ID字段，如果接口没有返回请告诉我
            side: (item.side || 'long').toLowerCase(), // 方向字段，用于显示"多"或"空"，如果接口没有返回请告诉我
            logoUrl: item.logoUrl || ''
        }))
      } catch (error) {
        console.error('加载委托数据失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.isOrderLoading = false
        uni.stopPullDownRefresh()
      }
    },

    /**
     * 加载充值提现数据
     */
    async loadRechargeData() {
      try {
        this.isRechargeLoading = true

        // 使用真实API
        const response = await getRechargeWithdraw({
          address: this.userAddress
        })
        console.log('充值提现数据:', response)
        const records = response.data || []

        this.rechargeList = records.map(item => ({
          time: item.time || '',
          type: item.type || '',
          usdc: item.usdc || '0',
          hash: item.hash || '' // 哈希字段，如果接口没有返回请告诉我
        }))
      } catch (error) {
        console.error('加载充值提现数据失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.isRechargeLoading = false
        uni.stopPullDownRefresh()
      }
    },
    
    /**
     * 缩短地址
     */
    shortenAddress(address) {
      if (!address || address.length < 10) return address || ''
      return `${address.slice(0, 6)}...${address.slice(-6)}`
    },
    
    /**
     * 获取币种图标
     */
    getCoinIcon(symbol) {
      if (this.coinIconMap[symbol]) {
        return this.coinIconMap[symbol]
      }
      return '/static/images/data/coin.png'
    },
    
    /**
     * 格式化未实现盈亏
     * 当为0时，不显示加号，显示黑色
     * 亏损时显示减号
     */
    formatPnl(pnl) {
      const num = parseFloat(pnl) || 0
      const absNum = Math.abs(num)

      // 当为0时，不显示加号
      if (num === 0) {
        return '$0.00'
      }

      const sign = num > 0 ? '+' : '-'
      if (absNum >= 10000) {
        return `${sign}$${(absNum / 10000).toFixed(2)}万`
      }
      return `${sign}$${absNum.toFixed(2)}`
    },

    /**
     * 格式化数量（做空时显示负号，支持万单位）
     */
    formatQuantity(szi, coin, side) {
      const num = parseFloat(szi) || 0
      const absNum = Math.abs(num)
      const sign = side === 'short' ? '-' : ''

      // 大于等于10000时显示为"万"格式
      if (absNum >= 10000) {
        return `${sign}${(absNum / 10000).toFixed(2)}万 ${coin}`
      }
      return `${sign}${absNum.toFixed(2)} ${coin}`
    },

    /**
     * 格式化价值
     * 使用公共工具函数
     */
    formatValue(value) {
      return formatValueUtil(value)
    },

    /**
     * 格式化资金费
     * 使用公共工具函数，当为0时，不显示加号
     */
    formatFundingFee(fee) {
      return formatSignedAmount(fee)
    },

    /**
     * 格式化价格
     * 使用公共工具函数，大于等于10000时显示为"万"格式
     */
    formatPrice(price) {
      return formatPriceUtil(price)
    },

    /**
     * 格式化保证金
     * 使用公共工具函数
     */
    formatMargin(margin) {
      return formatCurrency(margin)
    },

    /**
     * 判断是否为买入方向
     * @param {string} dir - 方向值（OPEN LONG, OPEN SHORT, CLOSE LONG, CLOSE SHORT 或 buy/sell）
     * @returns {boolean} true表示买入，false表示卖出
     */
    isBuyDir(dir) {
      if (!dir) return false
      const dirUpper = String(dir).toUpperCase().trim()
      // 根据 formatDir 的几种状态判断：OPEN LONG 和 CLOSE LONG 是买入方向
      if (dirUpper.includes('LONG')) {
        return true
      }
      // 兼容旧的 buy/sell 格式
      if (dirUpper === 'BUY') {
        return true
      }
      return false
    },

    /**
     * 格式化交易方向
     * @param {string} dir - 方向（OPEN LONG, OPEN SHORT, CLOSE LONG, CLOSE SHORT）
     * @returns {string} 格式化后的方向文本
     */
    formatDir(dir) {
      if (!dir) return '--'
      const dirMap = {
        'OPEN LONG': '开多',
        'OPEN SHORT': '开空',
        'CLOSE LONG': '平多',
        'CLOSE SHORT': '平空'
      }
      return dirMap[dir.toUpperCase()] || dir
    },

    /**
     * 格式化订单类型
     * @param {string} orderType - 订单类型（limit, market）
     * @returns {string} 格式化后的订单类型文本
     */
    formatOrderType(orderType) {
      if (!orderType) return '--'
      const typeMap = {
        'limit': '限价单',
        'market': '市价单'
      }
      return typeMap[orderType.toLowerCase()] || orderType
    },

    /**
     * 格式化交易数量
     * @param {string} sz - 数量
     * @param {string} coin - 币种
     * @param {string} dir - 方向（buy/sell）
     * @returns {string} 格式化后的数量，支持万单位
     */
    formatTradeQuantity(sz, coin, dir = 'buy') {
      const num = parseFloat(sz) || 0
      const absNum = Math.abs(num)
      // 使用 isBuyDir 方法判断，确保大小写不敏感
      const sign = !this.isBuyDir(dir) ? '-' : ''

      // 大于等于10000时显示为"万"格式
      if (absNum >= 10000) {
        return `${sign}${(absNum / 10000).toFixed(2)}万 ${coin}`
      }
      return `${sign}${absNum.toFixed(2)} ${coin}`
    },

    /**
     * 格式化委托数量
     * @param {string} sz - 数量
     * @param {string} coin - 币种
     * @returns {string} 格式化后的数量，支持万单位
     */
    formatOrderQuantity(sz, coin) {
      const num = parseFloat(sz) || 0

      // 大于等于10000时显示为"万"格式
      if (num >= 10000) {
        return `${(num / 10000).toFixed(2)}万 ${coin}`
      }
      return `${num.toFixed(2)} ${coin}`
    },

    /**
     * 格式化交易价值
     * 使用公共工具函数
     */
    formatTradeValue(sz, px) {
      const num = parseFloat(sz) || 0
      const price = parseFloat(px) || 0
      const value = num * price
      return formatPriceUtil(value)
    },

    /**
     * 格式化时间（MM-dd HH:mm）
     */
    formatTime(timeStr) {
      if (!timeStr) return '--'
      // 如果已经是格式化好的时间字符串，直接返回
      if (typeof timeStr === 'string' && timeStr.includes('-')) {
        // 提取 MM-dd HH:mm 格式
        const match = timeStr.match(/(\d{2}-\d{2}\s+\d{2}:\d{2})/)
        if (match) return match[1]
        return timeStr
      }
      // 如果是时间戳，转换为格式
      const timestamp = typeof timeStr === 'number' ? timeStr : parseInt(timeStr)
      if (timestamp) {
        const date = new Date(timestamp)
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        return `${month}-${day} ${hours}:${minutes}`
      }
      return timeStr
    },

    /**
     * 格式化充值提现价值
     * 使用公共工具函数
     */
    formatRechargeValue(usdc) {
      return formatCurrency(usdc)
    },

    /**
     * 格式化充值提现类型
     */
    formatRechargeType(type) {
      if (!type) return '--'
      // 根据图片，类型可能是：充值、提现、现货转账、send
      const typeMap = {
        'recharge': '充值',
        'withdraw': '提现',
        'deposit': '充值',
        'transfer': '现货转账',
        'send': 'send'
      }
      return typeMap[type.toLowerCase()] || type
    },

    /**
     * 复制地址到剪贴板
     */
    copyAddress() {
      if (!this.userAddress) {
        uni.showToast({
          title: '地址为空',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      uni.setClipboardData({
        data: this.userAddress,
        success: () => {
          uni.showToast({
            title: '地址已复制',
            icon: 'success',
            duration: 2000
          })
        },
        fail: (err) => {
          console.error('复制失败:', err)
          uni.showToast({
            title: '复制失败，请重试',
            icon: 'none',
            duration: 2000
          })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
/* 全局动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-20rpx);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.fade-in {
  animation: fadeIn 0.4s ease-out forwards;
}

.page {
  width: 100%;
}

/* 导航栏 */
.nav-bar {
  position: relative;
  width: 100%;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  box-shadow: 0 2rpx 12rpx rgba(0, 212, 170, 0.08);
  z-index: 100;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 24rpx;
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 8rpx;
  transition: all 0.3s ease;
  
  &:active {
    opacity: 0.6;
    transform: scale(0.95);
  }
}

.nav-title {
  flex: 1;
  font-size: 34rpx;
  font-weight: 700;
  color: #2a2b2f;
  text-align: center;
}

.nav-right {
  width: 40rpx;
}

/* 搜索容器 */
.search-container {
  padding: 24rpx;
  background: #ffffff;
  border-bottom: 1px solid #f0f3f8;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
  height: 72rpx;
  background: #f5f7fa;
  border-radius: 36rpx;
  border: 1px solid #e8eaed;
  transition: all 0.3s ease;
  overflow: hidden;

  &:focus-within {
    border-color: #00d4aa;
    background: #ffffff;
    box-shadow: 0 0 0 2rpx rgba(0, 212, 170, 0.1);
  }
}

.search-input {
  flex: 1;
  height: 100%;
  padding: 0 24rpx;
  padding-right: 120rpx; // 为搜索按钮留出空间
  background: transparent;
  font-size: 28rpx;
  color: #303133;
  border: none;
  outline: none;
}

.search-btn {
  position: absolute;
  right: 6rpx;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60rpx;
  padding: 0 24rpx;
  background: linear-gradient(135deg, #00d4aa 0%, #06CBB6 100%);
  border-radius: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 212, 170, 0.3);
  transition: all 0.3s ease;
  cursor: pointer;
  flex-shrink: 0;

  &:active {
    transform: translateY(-50%) scale(0.95);
    box-shadow: 0 1rpx 4rpx rgba(0, 212, 170, 0.2);
  }
}

.search-btn-text {
  font-size: 26rpx;
  font-weight: 600;
  color: #ffffff;
  white-space: nowrap;
}

/* 链上地址区域（在价值卡片内） */
.address-section {
  // margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.address-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex-wrap: nowrap;
}

.address-label {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  flex-shrink: 0;
  white-space: nowrap;
}

.address-value {
  flex: 1;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.95);
  font-family: 'Courier New', monospace;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.copy-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 6rpx 16rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  transition: all 0.3s ease;
  cursor: pointer;
  backdrop-filter: blur(10rpx);
  flex-shrink: 0;
  white-space: nowrap;
  
  &:active {
    transform: scale(0.95);
    background: rgba(255, 255, 255, 0.3);
  }
}

.copy-text {
  font-size: 22rpx;
  color: #ffffff;
  font-weight: 600;
}

/* 顶部价值卡片 - 带渐变和动画 */
.value-card {
  position: relative;
  padding: 48rpx 32rpx;
  margin: 24rpx;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 24rpx rgba(0, 212, 170, 0.15);
  animation: fadeIn 0.6s ease-out;
}

.value-card-content {
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.value-card-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #00d4aa 0%, #00a88a 50%, #008f75 100%);
  opacity: 1;
  z-index: 1;
}

.value-label {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  letter-spacing: 1rpx;
}

.value-amount {
  font-size: 56rpx;
  font-weight: 800;
  color: #ffffff;
  text-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  letter-spacing: 2rpx;
}

/* Tab切换栏 - 带滑动指示器动画和粘性布局 */
.tab-bar {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  background: #ffffff;
  margin: 0 24rpx 0rpx;
  border-radius: 16rpx;
  padding: 8rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 212, 170, 0.08);
  animation: slideIn 0.5s ease-out 0.2s backwards;
  z-index: 99; 
  flex-shrink: 0;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 56rpx;
  position: relative;
  z-index: 2;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &:active {
    transform: scale(0.95);
  }

  &.active {
    .tab-text {
      color: #ffffff;
      font-weight: 500;
    }
  }
}

.tab-text {
  font-size: 20rpx;
  color: #909399;
  font-weight: 400;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  z-index: 3;
}

.tab-indicator {
  position: absolute;
  left: 8rpx;
  top: 8rpx;
  bottom: 8rpx;
  width: calc(25% - 16rpx);
  background: linear-gradient(135deg, #00d4aa 0%, #00a88a 100%);
  border-radius: 12rpx;
  transition: left 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4rpx 12rpx rgba(0, 212, 170, 0.3);
  z-index: 1;
}

/* Tab内容区域 */
.tab-content {
  flex: 1;
  padding: 24rpx;
}

/* 加载和空状态 - 带动画 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
  gap: 24rpx;
  animation: fadeIn 0.3s ease-out;
}

.loading-text {
  font-size: 28rpx;
  color: #00d4aa;
  font-weight: 600;
  animation: pulse 1.5s ease-in-out infinite;
  letter-spacing: 2rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
  gap: 16rpx;
  animation: fadeIn 0.4s ease-out;
}

.empty-text {
  font-size: 28rpx;
  color: #c0c4cc;
  font-weight: 500;
}

/* 持仓列表样式 - 带入场动画 */
.position-list {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.position-item {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: slideIn 0.4s ease-out backwards;
  
  &:nth-child(1) { animation-delay: 0.1s; }
  &:nth-child(2) { animation-delay: 0.15s; }
  &:nth-child(3) { animation-delay: 0.2s; }
  &:nth-child(4) { animation-delay: 0.25s; }
  &:nth-child(5) { animation-delay: 0.3s; }
  
  &:active {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  }
}

.position-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 12rpx;
}

.direction-badge {
  width: 48rpx;
  height: 48rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  &.long {
    background: #00d4aa;
  }

  &.short {
    background: #f56c6c;
  }
}

.direction-text {
  font-size: 24rpx;
  font-weight: 700;
  color: #ffffff;
}

/* 仓位方向标识 */
.side-badge {
  width: 40rpx;
  height: 40rpx;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-weight: 700;

  &.long {
    background: #00d4aa;
  }

  &.short {
    background: #f56c6c;
  }
}

.side-text {
  font-size: 20rpx;
  font-weight: 700;
  color: #ffffff;
}

.coin-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  flex-shrink: 0;
  background: #f5f7fa;
}

.coin-name {
  font-size: 32rpx;
  font-weight: 700;
  color: #303133;
}

.position-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8rpx;
  gap: 12rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.position-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;

  &:last-child {
    text-align: right;
  }
}

.label {
  font-size: 22rpx;
  color: #909399;
}

.value {
  font-size: 24rpx;
  color: #000000;
  font-weight: 400;

  &.pnl {
    font-size: 26rpx;
    font-weight: 600;
  }

  &.profit {
    color: #00d4aa;
  }

  &.loss {
    color: #f56c6c;
  }

  // 当值为0时，显示黑色
  &:not(.profit):not(.loss) {
    color: #000000;
  }

  &.leverage {
    color: #000000;
    font-weight: 400;
  }

  &.funding-fee {
    font-size: 24rpx;
    font-weight: 400;
  }
}

/* 交易列表样式 - 带入场动画 */
.trade-list {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.trade-item {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: slideIn 0.4s ease-out backwards;
  
  &:nth-child(1) { animation-delay: 0.1s; }
  &:nth-child(2) { animation-delay: 0.15s; }
  &:nth-child(3) { animation-delay: 0.2s; }
  &:nth-child(4) { animation-delay: 0.25s; }
  &:nth-child(5) { animation-delay: 0.3s; }
  
  &:active {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  }
}

.trade-top-row {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.trade-dir-badge {
  width: 48rpx;
  height: 48rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  
  &.buy {
    background: #00d4aa;
  }
  
  &.sell {
    background: #f56c6c;
  }
}

.dir-text {
  font-size: 24rpx;
  font-weight: 700;
  color: #ffffff;
}

.trade-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.trade-hash {
  flex: 1;
  font-size: 24rpx;
  color: #303133;
  font-family: 'Courier New', monospace;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
}

.trade-row {
  display: flex;
  justify-content: space-between;
  gap: 12rpx;
  margin-bottom: 8rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.trade-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;

  &:last-child {
    text-align: right;
  }
}

.trade-label {
  font-size: 22rpx;
  color: #909399;
}

.trade-quantity {
  font-size: 24rpx;
  color: #000000;
  font-weight: 400;

  &.sell-quantity {
    color: #f56c6c;
  }
}

.trade-operation {
  font-size: 24rpx;
  color: #000000;
  font-weight: 400;
}

.trade-value,
.trade-price {
  font-size: 24rpx;
  color: #000000;
  font-weight: 400;
}

.trade-time {
  font-size: 28rpx;
  color: #606266;
}

/* 委托列表样式 - 带入场动画 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.order-item {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: slideIn 0.4s ease-out backwards;
  
  &:nth-child(1) { animation-delay: 0.1s; }
  &:nth-child(2) { animation-delay: 0.15s; }
  &:nth-child(3) { animation-delay: 0.2s; }
  &:nth-child(4) { animation-delay: 0.25s; }
  &:nth-child(5) { animation-delay: 0.3s; }
  
  &:active {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  }
}

.order-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.order-dir-badge {
  width: 48rpx;
  height: 48rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &.long {
    background: #00d4aa;
  }
  
  &.short {
    background: #f56c6c;
  }
}

.order-dir-text {
  font-size: 24rpx;
  font-weight: 700;
  color: #ffffff;
}

.order-coin {
  font-size: 32rpx;
  font-weight: 700;
  color: #303133;
}

.order-row {
  display: flex;
  justify-content: space-between;
  gap: 12rpx;
  margin-bottom: 8rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.order-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;

  &:last-child {
    text-align: right;
  }
}

.label {
  font-size: 22rpx;
  color: #909399;
  font-weight: 400;
}

.value {
  font-size: 24rpx;
  color: #000000;
  font-weight: 400;
}

.order-type {
  color: #000000;
  font-weight: 400;
}

.order-id {
  color: #606266;
  font-family: 'Courier New', monospace;
  font-weight: 400;
}

/* 充值提现列表样式 - 带入场动画 */
.recharge-list {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.recharge-item {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: slideIn 0.4s ease-out backwards;
  
  &:nth-child(1) { animation-delay: 0.1s; }
  &:nth-child(2) { animation-delay: 0.15s; }
  &:nth-child(3) { animation-delay: 0.2s; }
  &:nth-child(4) { animation-delay: 0.25s; }
  &:nth-child(5) { animation-delay: 0.3s; }
  
  &:active {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  }
}

.recharge-row {
  display: flex;
  justify-content: space-between;
  gap: 12rpx;
  margin-bottom: 8rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.recharge-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;

  &:last-child {
    text-align: right;
  }
}

.recharge-label {
  font-size: 22rpx;
  color: #909399;
  font-weight: 400;
}

.recharge-value {
  font-size: 24rpx;
  color: #000000;
  font-weight: 400;

  &.recharge-type {
    color: #000000;
    font-weight: 400;
  }

  &.recharge-hash {
    font-size: 22rpx;
    color: #606266;
    font-family: 'Courier New', monospace;
    word-break: break-all;
    font-weight: 400;
  }
}

</style>
<style>
page{
  background: linear-gradient(180deg, #f0faf8 0%, #f5f7fa 100%);
}

</style>

